import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const cartItems = ref(JSON.parse(localStorage.getItem('cartItems') || '[]'))
  
  // 计算属性
  const totalCount = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0)
  })
  
  const totalPrice = computed(() => {
    return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
  })
  
  const selectedItems = computed(() => {
    return cartItems.value.filter(item => item.selected)
  })
  
  const selectedTotalPrice = computed(() => {
    return selectedItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
  })

  // 添加商品到购物车
  const addToCart = (product) => {
    const existingItem = cartItems.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += 1
    } else {
      cartItems.value.push({
        ...product,
        quantity: 1,
        selected: true
      })
    }
    
    saveToLocalStorage()
  }

  // 从购物车移除商品
  const removeFromCart = (productId) => {
    const index = cartItems.value.findIndex(item => item.id === productId)
    if (index > -1) {
      cartItems.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 更新商品数量
  const updateQuantity = (productId, quantity) => {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      if (quantity <= 0) {
        removeFromCart(productId)
      } else {
        item.quantity = quantity
        saveToLocalStorage()
      }
    }
  }

  // 切换商品选中状态
  const toggleSelect = (productId) => {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      item.selected = !item.selected
      saveToLocalStorage()
    }
  }

  // 全选/取消全选
  const toggleSelectAll = (selected) => {
    cartItems.value.forEach(item => {
      item.selected = selected
    })
    saveToLocalStorage()
  }

  // 清空购物车
  const clearCart = () => {
    cartItems.value = []
    saveToLocalStorage()
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('cartItems', JSON.stringify(cartItems.value))
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    const saved = localStorage.getItem('cartItems')
    if (saved) {
      cartItems.value = JSON.parse(saved)
    }
  }

  return {
    cartItems,
    totalCount,
    totalPrice,
    selectedItems,
    selectedTotalPrice,
    addToCart,
    removeFromCart,
    updateQuantity,
    toggleSelect,
    toggleSelectAll,
    clearCart,
    loadFromLocalStorage
  }
})
